<template>

  <div class="gep-output-calculator">

    <div class="supply-material">
      <h2 class="title">物质供给价值核算</h2>
      <div class="vepD4-input-container">
        <div class="vepD4-input-row">
          <!--          直接售卖物质产品纯收益-->
          <label class="label">直接售卖产品纯收益:</label>
          <input type="text" v-model="vepSupplyServiceStore.inDirectProductProfit" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"
          />
          <span>（万元）</span>
        </div>
        <div class="vepD4-input-row">

        </div>
        <div class="vepD4-input-row">
          <label class="label">精深加工产品纯收益:</label>
          <input type="text" v-model="vepSupplyServiceStore.inProcessProfit" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"/>
          <span>（万元）</span>
        </div>
        <div class="vepD4-input-row">

        </div>
      </div>
    </div>

    <div class="cultural-service">
      <!--      {{vepCulturalServiceStore.outVepCulturalService}} = {{vepCulturalServiceStore.outLandscapeAppreciation}} + {{vepCulturalServiceStore.outLeisureRecreation}} + {{vepCulturalServiceStore.outTourismHealth}}-->
      <h2 class="title">文化服务价值核算
      </h2>
      <div class="vepD4-input-container">
        <div class="vepD4-input-row">
          <label class="label">旅游康养年纯收益:</label>
          <input type="text" v-model="vepCulturalServiceStore.inTourismHealthcareProfit" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"/>
          <span>（万元）</span>
        </div>
        <div class="vepD4-input-row">
          <label class="label">酒店房间数量:</label>
          <input type="text" v-model="vepCulturalServiceStore.inHotelRooms" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"/>
          <span>（间）</span>
        </div>
        <div class="vepD4-input-row">
          <label class="label">酒店价格:</label>
          <input type="text" v-model="vepCulturalServiceStore.inRoomPrice" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"/>
          <span>（元/间）</span>
        </div>

        <div class="vepD4-input-row">
          <label class="label">年入住率:</label>
          <input type="text" v-model="vepCulturalServiceStore.inOccupancyRate" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"/>
          <span>（%）</span>
        </div>

        <div class="vepD4-input-row">
          <label class="label">房租售交易年纯收益:</label>
          <input type="text" v-model="vepCulturalServiceStore.inPropertyProfit" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"/>
          <span>（万元）</span>
        </div>


        <div class="vepD4-input-row">
          <label class="label">每日客流量:</label>
          <input type="text" v-model="vepCulturalServiceStore.dailyPassengerFlowPeople" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"/>
          <span>（人/天）</span>
        </div>

        <div class="vepD4-input-row">
          <label class="label">人均日消费:</label>
          <input type="text" v-model="vepCulturalServiceStore.perCapitaDailySpendingYuan" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"/>
          <span>（元/人）</span>
        </div>


        <div class="vepD4-input-row">
          <label class="label">门票:</label>
          <input type="text" v-model="vepCulturalServiceStore.ticketPricePerPerson" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"/>
          <span>（元/人）</span>
        </div>
      </div>
    </div>
    <!--    <button type="button" @click="test" class="clear-button ">test</button>-->


    <div class="regulation-service">
      <h2 class="title">调节服务价值核算</h2>
      <div class="vepD4-input-container">
        <div class="vepD4-input-row">
          <label class="label">项目占地面积:</label>
          <input type="text" v-model="vepRegulationServiceStore.inProjectLandArea" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"/>
          <span>（km2）</span>
        </div>

        <div class="vepD4-input-row">
          <label class="label">所在区县面积:</label>
          <input type="text" v-model="vepRegulationServiceStore.projectTownArea" class="value-input"
                 @keydown="handleInputKeydown"
                 @input="handleInput"
                 inputmode="decimal"/>
          <span>（km2）</span>
        </div>

        <!--        <div class="vepD4-input-row">-->
        <!--          <label class="label">所在区县调节GEP（万元）:</label>-->
        <!--          <input type="text" v-model="totalRegulationServicelData" class="value-input"/>-->
        <!--        </div>-->

      </div>
    </div>

    <!--     计算按钮和结果展示-->
    <!-- 提交按钮 -->
    <div class="bottom-button-container" style="display: flex;justify-content: space-around;padding-left: 10px">

      <button type="submit" @click="calculateVEP"
              class="bg-green-800 text-white hover:bg-green-700 font-bold py-2 px-4 rounded inline-flex items-center">
        <svg class="w-6 h-6 mr-2 dark:text-white" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24"
             height="24" fill="none" viewBox="0 0 24 24">
          <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M8.5 11.5 11 14l4-4m6 2a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"/>
        </svg>
        <span>提交</span>
      </button>

      <button type="submit" @click="saveDataVEP"
              class="bg-green-800 text-white hover:bg-orange-500 font-bold py-2 px-4 rounded inline-flex items-center">
        <svg class="fill-current w-4 h-4 mr-2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
          <path d="M13 8V2H7v6H2l8 8 8-8h-5zM0 18h20v2H0v-2z"/>
        </svg>
        <span>保存输入</span>
      </button>

      <button type="button" @click="handleClear"
              class="bg-green-800 text-white hover:bg-red-500  font-bold py-2 px-4 rounded inline-flex items-center">
        <svg class="w-6 h-6 mr-2 dark:text-white" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24"
             height="24" fill="none" viewBox="0 0 24 24">
          <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M5 7h14m-9 3v8m4-8v8M10 3h4a1 1 0 0 1 1 1v3H9V4a1 1 0 0 1 1-1ZM6 7h12v13a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V7Z"/>
        </svg>
        <span>清空</span>
      </button>

    </div>
  </div>

</template>


<script setup>
import {ref, watch} from 'vue';
import {storeToRefs} from "pinia";
import {
  useVepDataStore,
  useVepCulturalServiceStore,
  useVepRegulationServiceStore,
  useVepSupplyServiceStore
} from "@/stores/vep.ts";
import {useRouter} from "vue-router";
// import {saveInputVEP} from "api/vepApi";
import {useLoginStore} from "@/stores/login";
import {getVepParameterByPath, updateVepParameterByPath, updateVepResultByPath} from "api/services/vepService";
import {ElMessage} from "element-plus";
import {handleInput, handleInputKeydown} from "api/services/gepFormService";

const vepSupplyServiceStore = useVepSupplyServiceStore();
const vepRegulationServiceStore = useVepRegulationServiceStore();
const vepCulturalServiceStore = useVepCulturalServiceStore();

const {outVepSupplyService} = storeToRefs(vepSupplyServiceStore);
const {outVepCulturalService} = storeToRefs(vepCulturalServiceStore);
const {outVepRegulationService} = storeToRefs(vepRegulationServiceStore);


const vepDataStore = useVepDataStore();
const {
  vepYear,
  vepCity,
  vepDistrict,
  isSelected,
  vepTown,
  vepName,
  vepValue,
  isSubmitted,
  count
} = storeToRefs(vepDataStore);
const message = ref('');

const loginStore = useLoginStore();

// 计算VEP的方法
async function calculateVEP() {
  // 检查是否选择了地区
  // todo 打开注释
  if (vepName.value === '') {
    message.value = "请填写项目名称！"
    ElMessage.warning(message.value);
    return;
  }
  if (vepTown.value === '') {
    message.value = "请选择地区！"
    ElMessage.warning(message.value);
    return;
  }
  if (vepRegulationServiceStore.inProjectLandArea === 0) {
    message.value = "请填报数据！"
    ElMessage.warning(message.value);
    return;
  }
  // if (vepRegulationServiceStore.inCodCr === 0){
  //   alert("数据未填报完全！")
  //   return;
  // }
  vepValue.value = outVepSupplyService.value + outVepCulturalService.value + outVepRegulationService.value;

  console.log('calculateVep:vepValue', vepValue.value);
  isSubmitted.value = true;
  count.value += 1;
  await saveDataVEP();
  console.log('calculateVep:saveDataVEP', vepValue.value);
  await saveResultVEP();
  console.log('calculateVep:saveResultVEP', vepValue.value);

}

import {townToProjectTownAreaMap} from '@/utils/areaMapping';


watch(vepTown, (newValues) => {
  console.log('vepTown有变化', newValues);
  if (newValues && townToProjectTownAreaMap[newValues]) {
    vepRegulationServiceStore.projectTownArea = townToProjectTownAreaMap[newValues];
  } else {
    vepRegulationServiceStore.projectTownArea = 0; // 默认值或空值处理
  }
});


function resetAllFormFieldsToZero() {
  // 供给服务字段清零
  vepSupplyServiceStore.$patch({
    inDirectProductProfit: 0,
    inProcessProfit: 0
  });

  // 调节服务字段清零
  vepRegulationServiceStore.$patch({
    inProjectLandArea: 0,
    projectTownArea: vepRegulationServiceStore.projectTownArea,
    // regionRegulationService: 0
  });

  // 文化服务字段清零
  vepCulturalServiceStore.$patch({
    inTourismHealthcareProfit: 0,
    inHotelRooms: 0,
    inRoomPrice: 0,
    inOccupancyRate: 0,

    inPropertyProfit: 0,
    dailyPassengerFlowPeople: 0,
    perCapitaDailySpendingYuan: 0,
    ticketPricePerPerson: 0
  });
}


watch(isSelected, async (newValues) => {
  if (!newValues) return;

  try {
    const response = await getVepParameterByPath(Number(vepYear.value), vepCity.value, vepDistrict.value, vepTown.value, vepName.value);
    console.log('response——input', response);

    // 更新供给服务 Store
    vepSupplyServiceStore.$patch({
      inDirectProductProfit: Number(response.data.directSalesRevenue) || 0,
      inProcessProfit: Number(response.data.processedProductsRevenue) || 0,
    });

    // 更新调节服务 Store
    vepRegulationServiceStore.$patch({
      inProjectLandArea: Number(response.data.projectArea) || 0,
      // projectTownArea: Number(response.data.townArea) || vepRegulationServiceStore.projectTownArea,
      // regionRegulationService: Number(response.data.regulationServiceValue) || 0

    });

    // 更新文化服务 Store
    vepCulturalServiceStore.$patch({
      inTourismHealthcareProfit: Number(response.data.tourismHealthRevenue) || 0,
      inHotelRooms: Number(response.data.roomCount) || 0,
      inRoomPrice: Number(response.data.roomPrice) || 0,
      inOccupancyRate: Number(response.data.averageOccupancyRate) || 0,

      inPropertyProfit: Number(response.data.realEstateRevenue) || 0,
      dailyPassengerFlowPeople: Number(response.data.dailyVisitorFlow) || 0,
      perCapitaDailySpendingYuan: Number(response.data.perCapitaDailyConsumption) || 0,
      ticketPricePerPerson: Number(response.data.ticketPrice) || 0
    });

    isSelected.value = false;
    console.log('获取资源成功后isSelected:', isSelected.value);

  } catch (error) {
    console.error('获取 GEP 参数失败:', error);

    // 请求失败，清空所有输入字段为 0
    resetAllFormFieldsToZero();

    // ElMessage.warning('未查询到对应年份和地区的参数配置，已清空输入框');
    isSelected.value = false;
  }
});


const router = useRouter();

// 清空表单处理函数
function handleClear() {
  // 用刷新页面代替
  // window.location.reload();

  router.push('/vepCalcDevNan');
  setTimeout(() => {

    console.log('tiaozhuan', isSubmitted.value)
    router.push('/vepCalcDev');
  }, 300);
}

// 保存vep表单输入数据
async function saveDataVEP() {
  const year = Number(vepYear.value);
  const city = vepCity.value;
  const district = vepDistrict.value;
  const town = vepTown.value;
  const name = vepName.value;
  console.log('saveDataVEP:vepName', name)

  if (vepCity.value === '市') {
    // alert("请选择地区！")
    message.value = "请选择地区！"
    ElMessage.warning(message.value);
    return;
  }
  if (vepName.value === '') {
    // alert("请选择地区！")
    message.value = "请输入项目名称！"
    ElMessage.warning(message.value);
    return;
  }

  // 组装数据
  const vepData = {
    directSalesRevenue: Number(vepSupplyServiceStore.inDirectProductProfit),
    processedProductsRevenue: Number(vepSupplyServiceStore.inProcessProfit),

    projectArea: Number(vepRegulationServiceStore.inProjectLandArea),
    townArea: Number(vepRegulationServiceStore.projectTownArea),
    regulationServiceValue: Number(vepRegulationServiceStore.regionRegulationService),

    tourismHealthRevenue: Number(vepCulturalServiceStore.inTourismHealthcareProfit),
    roomCount: Number(vepCulturalServiceStore.inHotelRooms),
    roomPrice: Number(vepCulturalServiceStore.inRoomPrice),
    averageOccupancyRate: Number(vepCulturalServiceStore.inOccupancyRate),
    realEstateRevenue: Number(vepCulturalServiceStore.inPropertyProfit),
    dailyVisitorFlow: Number(vepCulturalServiceStore.dailyPassengerFlowPeople),
    perCapitaDailyConsumption: Number(vepCulturalServiceStore.perCapitaDailySpendingYuan),
    ticketPrice: Number(vepCulturalServiceStore.ticketPricePerPerson),
    updater: loginStore.username,
  };
  console.log('vepData', vepData);

  try {
    const result = await updateVepParameterByPath(year, city, district, town, name, vepData);
    ElMessage.success('参数更新成功');
    console.log('更新成功:', result);
  } catch (error) {
    ElMessage.error('保存失败，请重试');
    console.error('保存 GEP 参数失败:', error);
  }
}

// 保存vep计算结果数据
async function saveResultVEP() {
  const year = Number(vepYear.value);
  const city = vepCity.value;
  const district = vepDistrict.value;
  const town = vepTown.value;
  const name = vepName.value;
  console.log('saveResultVEP:vepName', name)

  // todo 组装数据
  const vepResultData = {
    vepResult: vepSupplyServiceStore.outVepSupplyService + vepRegulationServiceStore.outVepRegulationService + vepCulturalServiceStore.outVepCulturalService,
    provisioningServices: vepSupplyServiceStore.outVepSupplyService,

    regulatingServices: vepRegulationServiceStore.outVepRegulationService,

    culturalServices: vepCulturalServiceStore.outVepCulturalService,
    updater: loginStore.username,
    imageUrl: 'https://fzs-yanshan.oss-cn-beijing.aliyuncs.com/vep-project/vep-project-default.jpg'

  };
  console.log('vepResultData', vepResultData);

  try {
    const result = await updateVepResultByPath(year, city, district, town, name, vepResultData);
    ElMessage.success('结果保存成功');
    console.log('更新成功:', result);
  } catch (error) {
    ElMessage.error('保存失败，请重试');
    console.error('保存 GEP 参数失败:', error);
  }
}

</script>

<style scoped>

.title {
  font-size: 20px;
  font-weight: bold;
  height: 40px;
  text-align: left;
  color: #caeffa;
  padding-left: 10px;
  padding-top: 5px;
  background-color: #194c51;
}


</style>

